package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.apache.xmlbeans.impl.jam.JamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.RedisKeyConstants.IOT_ALL_PRODUCT_LIST;

/**
 * 设备管理Service业务层处理
 * 
 * @author king
 * @date 2025-05-13
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询设备管理
     * 
     * @param id 设备管理主键
     * @return 设备管理
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备管理列表
     * 
     * @param device 设备管理
     * @return 设备管理
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备管理
     * 
     * @param device 设备管理
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备管理
     * 
     * @param ids 需要删除的设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备管理信息
     * 
     * @param id 设备管理主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 获取产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest request = new ListProductsRequest();
        //设置分页
        request.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(request);

        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        //存入redis
        redisTemplate.opsForValue().set(IOT_ALL_PRODUCT_LIST, products);
    }

    @Override
    public List<ProductVo> allProduct() {
        List<ProductSummary> products = (List<ProductSummary>) redisTemplate.opsForValue().get(IOT_ALL_PRODUCT_LIST);
        if(CollUtil.isEmpty(products)){
            return List.of();
        }
        List<ProductVo> voList = BeanUtil.copyToList(products, ProductVo.class);
        return voList;
    }

    /**
     *注册设备
     */
    @Override
    public void register(DeviceDto dto) {
        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        long count = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName())
        );
        if(count > 0){
            throw new RuntimeException("设备名称重复");
        }

        //2.检验设备标识码nodeId是否重复
        long countNodeId = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getNodeId()), Device::getNodeId, dto.getNodeId())
        );
        if(countNodeId > 0){
            throw new RuntimeException("设备标识码重复");
        }
        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品(产品唯一标识)
        long countProduct = count(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getLocationType, dto.getLocationType())
                        .eq(Device::getBindingLocation, dto.getBindingLocation())
                        .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                        .eq(Device::getProductKey, dto.productKey)
        );
        if(countProduct > 0){
            throw new RuntimeException("同一位置绑定了同一类产品");
        }
        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        body.withAuthInfo(authInfo);
        request.withBody(body);
        String iotId;
        try {
            AddDeviceResponse response = client.addDevice(request);
            iotId = response.getDeviceId();
        } catch (Exception e) {
            throw new RuntimeException("设备注册失败");
        }
        //5.设备数据保存到数据库
        //对象属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setIotId(iotId);
        //保存
        save(device);
    }

    @Override
    public DeviceDetailVo showDeviceDetail(String iotId) {
        //先查IOT
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        String deviceStatus = "";
        String activeTimeStr = "";
        try {
            ShowDeviceResponse response = client.showDevice(request);
            deviceStatus = response.getStatus();
            activeTimeStr = response.getActiveTime();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询设备详情失败");
        }
        //在查数据库
        Device device = getOne(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getIotId, iotId)
        );
        //封装vo
        DeviceDetailVo detailVo = BeanUtil.copyProperties(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(deviceStatus);
        if(StringUtils.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            detailVo.setActiveTime(activeTime);
        }
        return detailVo;
    }

    /**
     * 查看设备上报的数据
     * @param iotId
     * @return
     */
    @Override
    public List<Map> queryServiceProperties(String iotId) {

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);
            Object properties = response.getShadow().get(0).getReported().getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            String eventTimeStr = response.getShadow().get(0).getReported().getEventTime();

            List list = new ArrayList<>();

            //处理上报时间日期
            LocalDateTime activeTime =  LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            jsonObject.forEach((key, value) -> {
                HashMap<Object, Object> map = new HashMap<>();
                map.put("functionId", key);
                map.put("value", value);
                map.put("eventTime", eventTime);
                list.add(map);
            });

            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("查询设备详情失败");
        }
    }
}
